package com.huawei.hmsdemo10086.Fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;

import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.huawei.hmsdemo10086.POJO.ShopDetatil;
import com.huawei.hmsdemo10086.R;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment {


    private View view;
    private MapView mMapView;
    private LocationClient locationClient;
    private BaiduMap baiduMap;
    private boolean firstLocation;
    private BitmapDescriptor mCurrentMarker;
    private PoiSearch mPoiSearch;
    List<ShopDetatil> shopDetatils;
    private RoutePlanSearch mSearch;
    private LatLng nowLocation;
    private WalkingRouteOverlay last_overlay = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view =  inflater.inflate(R.layout.fragment_home, container, false);


        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(getActivity(), permissions, 1);
        }


        //此方法要再setContentView方法之前实现
        SDKInitializer.initialize(getActivity().getApplicationContext());
        mPoiSearch = PoiSearch.newInstance();
        mMapView =(MapView)view.findViewById(R.id.baiDuMv);
        baiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15f);
        baiduMap.setMapStatus(msu);
        // 定位初始化
        locationClient = new LocationClient(getContext());
        mSearch = RoutePlanSearch.newInstance();
        firstLocation =true;
        // 设置定位的相关配置
        shopDetatils = new ArrayList<>();
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        locationClient.setLocOption(option);

        /*OnGetRoutePlanResultListener walkListener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
                //创建WalkingRouteOverlay实例
                if(last_overlay != null)
                {
                    last_overlay.removeFromMap();
                }
                WalkingRouteOverlay overlay = new WalkingRouteOverlay(baiduMap);

                if(walkingRouteResult.getRouteLines() == null)
                {
                    return;
                }
                if (walkingRouteResult.getRouteLines().size() > 0) {
                    //获取路径规划数据,(以返回的第一条数据为例)
                    //为WalkingRouteOverlay实例设置路径数据
                    overlay.setData(walkingRouteResult.getRouteLines().get(0));
                    //在地图上绘制WalkingRouteOverlay
                    overlay.addToMap();
                    last_overlay = overlay;
                }
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }

        };
        mSearch.setOnGetRoutePlanResultListener(walkListener);


        // 设置自定义图标
        BitmapDescriptor myMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.address);
        OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){
            public void onGetPoiResult(PoiResult result){
                System.out.println(result.getAllPoi());
                shopDetatils.clear();
                for(int i = 0; i < 10 ; i++)
                {
                    //System.out.println(result.getAllPoi().get(i).getName());
                    LatLng point = result.getAllPoi().get(i).getLocation();
                    //构建Marker图标
                    BitmapDescriptor bitmap = BitmapDescriptorFactory
                            .fromResource(R.drawable.address);
//构建MarkerOption，用于在地图上添加Marker
                    OverlayOptions option = new MarkerOptions()
                            .position(point)
                            .icon(bitmap);


//在地图上添加Marker，并显示
                    String name = result.getAllPoi().get(i).getName()+"";
                    String phone = result.getAllPoi().get(i).getPhoneNum()+"";
                    String address = result.getAllPoi().get(i).getAddress()+"";

                    System.out.println(result.getAllPoi().get(i).getLocation());

                    ShopDetatil shopDetatil = new ShopDetatil();
                    shopDetatil.setPosition(result.getAllPoi().get(i).getLocation());
                    shopDetatil.setName(name);
                    shopDetatil.setAddress(address);
                    shopDetatil.setPhone(phone);
                    shopDetatils.add(shopDetatil);
                    //shopDetatil.setX(result.getAllPoi().get(i));
                    baiduMap.addOverlay(option);

                }
                baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker) {
                        ShopDetatil shopDetatil = new ShopDetatil();
                        for(int i = 0 ; i < shopDetatils.size() ; i++)
                        {
                            if(shopDetatils.get(i).getPosition() == marker.getPosition())
                            {
                                shopDetatil = shopDetatils.get(i);
                                break;
                            }
                        }

                        Button button = new Button(getActivity().getApplicationContext());
                        button.setBackgroundResource(R.drawable.bubble);
                        button.setText(shopDetatil.getName() + '\n' + shopDetatil.getAddress() + '\n' + shopDetatil.getPhone());
                        PlanNode stNode = PlanNode.withCityNameAndPlaceName("厦门", "厦门理工学院精工园1号楼");
                        PlanNode enNode = PlanNode.withCityNameAndPlaceName("厦门", shopDetatil.getName());
//构造InfoWindow
//point 描述的位置
//-100 InfoWindow相对于point在y轴的偏移量
                        InfoWindow mInfoWindow = new InfoWindow(button, shopDetatil.getPosition(), -100);
                        mSearch.walkingSearch((new WalkingRoutePlanOption())
                                .from(stNode)
                                .to(enNode));
//使InfoWindow生效
                        baiduMap.showInfoWindow(mInfoWindow);
                        return false;
                    }
                });
            }


            public void onGetPoiDetailResult(PoiDetailResult result){

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        };








        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                // map view 销毁后不在处理新接收的位置

                if (location == null || mMapView == null)
                    return;
                // 构造定位数据
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                // 设置定位数据
                baiduMap.setMyLocationData(locData);

                // 第一次定位时，将地图位置移动到当前位置
                if (firstLocation)
                {
                    firstLocation = false;
                    LatLng xy = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(xy);
                    baiduMap.animateMapStatus(status);
                }

                mPoiSearch.setOnGetPoiSearchResultListener(poiListener);


                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                LatLng latLng = new LatLng(latitude,longitude);
                nowLocation = latLng;
                mPoiSearch.searchNearby(new PoiNearbySearchOption()
                        .keyword("宠物")
                        .location(latLng)
                        .radius(100000)
                        .pageNum(1));
                baiduMap.clear();


            }
        });*/
        return view;
    }

    @Override
    public void onStart()
    {
        // 如果要显示位置图标,必须先开启图层定位
        baiduMap.setMyLocationEnabled(true);
        if (!locationClient.isStarted())
        {
            locationClient.start();
        }
        super.onStart();
    }

    @Override
    public void onStop()
    {
        // 关闭图层定位
        baiduMap.setMyLocationEnabled(false);
        locationClient.stop();
        super.onStop();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy()
        mMapView.onDestroy();
        mMapView = null;
    }

    @Override
    public void onResume()
    {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()
        mMapView.onResume();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()
        mMapView.onPause();
    }

}